package com.iqiyi.pps.epg.web.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.core.model.record.RecordPlan;
import com.iqiyi.pps.epg.core.model.record.RecordTask;
import com.iqiyi.pps.epg.core.model.record.RecordTaskStatus;
import com.iqiyi.pps.epg.core.model.record.RecordVideo;
import com.iqiyi.pps.epg.core.service.record.IRecordService;
import com.iqiyi.pps.epg.core.utils.ApiAlertPlatFormUtil;
import com.iqiyi.pps.epg.core.utils.ApiRecordNotifyUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2018/4/22.
 */
public class RecordTaskNotifyTrigger {
    private static Logger logger = LoggerFactory.getLogger(RecordTaskNotifyTrigger.class);
    @Autowired
    private IRecordService recordService;

    public void task() {
        long startTime = System.currentTimeMillis();
        logger.info("[RecordTaskNotifyTrigger] start trigger");

        //获取 任务结束时间后 5分钟 可用任务， 调取正坤 点播接口 ，插入视频列表
        List<RecordTask> resultList = recordService.queryRecordTaskForGetVideo();
        ExecutorService exec = Executors.newFixedThreadPool(3);
        for (RecordTask temp : resultList) {
            exec.execute(new TaskExecutor(temp));
        }
        logger.info("[RecordTaskNotifyTrigger] end trigger time:" + (System.currentTimeMillis() - startTime));
        logger.info("[RecordTaskNotifyTrigger] end trigger");
    }

    private class TaskExecutor implements Runnable {
        private RecordTask task;

        public TaskExecutor(RecordTask task) {
            this.task = task;
        }

        @Override
        public void run() {
            try {
                logger.info("[RecordTaskNotifyTrigger] run --> \n" + task);
                JSONObject ret = ApiRecordNotifyUtil.notifyGetVideo(task);
                HashMap<String, String> params = task.getParams();
                if (ret != null && Constants.CODE_SUC.equals(ret.getString("code"))) {
                    task.setTaskStatus(RecordTaskStatus.NOTIFY_START_RECORD.getStatusIndex());
                    recordService.editRecordTask(task);
                    //插入视频列表 record_video
                    RecordVideo recordVideo = new RecordVideo();

                    recordVideo.setChannelId(Long.parseLong(params.get("channelId")));
                    recordVideo.setChannelSignalId(Long.parseLong(params.get("channelSignalId")));
                    recordVideo.setSignalId(Long.parseLong(params.get("signal_id")));
                    recordVideo.setTaskId(task.getId());
                    recordVideo.setVideoStatus(200);
                    recordVideo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    recordVideo.setStatus(1);
                    recordService.saveRecordVideo(recordVideo);
                } else {
                    task.setTaskStatus(RecordTaskStatus.NOTIFY_START_RECORD_FAIL.getStatusIndex());
                    recordService.editRecordTask(task);
                    RecordPlan recordPlan = recordService.getRecordPlanById(task.getPlanId());
                    if (canUseAlert(recordPlan)) {
                        JSONObject content = new JSONObject();
                        content.put("content", "[channelId=" + params.get("channelId")  + "][planId=" + task.getPlanId() + "][taskId=" + task.getId()+ "] 任务异常 " + RecordTaskStatus.NOTIFY_START_RECORD_FAIL);
                        ApiAlertPlatFormUtil.doSend(ApiAlertPlatFormUtil.TOPIC_ID_LIVE_RECORD, ApiAlertPlatFormUtil.SECRET_KEY_EPG, content.toJSONString(), getWorkers(recordPlan.getProjectWorkers()), recordPlan.getNotifyType());
                    }
                }
            } catch (Exception e) {
                logger.info("[RecordTaskNotifyTrigger] [exception={}]" + e);

            }
        }
    }

    private boolean canUseAlert(RecordPlan recordPlan) {
        return recordPlan.getProjectWorkers() != null && recordPlan.getProjectWorkers().length() > 2 && recordPlan.getNotifyType() > 0;
    }

    private String getWorkers(String projectWorkers) {
        StringBuilder sb = new StringBuilder();
        if (projectWorkers != null && projectWorkers.length() > 2) {
            JSONArray jsonArray = JSONArray.parseArray(projectWorkers);
            Iterator<Object> t = jsonArray.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                sb.append(entity.getString("id").split("@")[0]);
                sb.append(",");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        return sb.toString();
    }
}
